<template>
  <!--  外框架-->
  <div class="framework1">
    <!--      内框架-->
    <div class="framework2">
      <div class="top-class-table">
        <div class="header">
          <div style="margin-left: 10px;font-weight: bold">辖区管理->辖区人员</div>
        </div>
        <!--      按钮行-->
        <div class="button_group">
          <el-button-group>
            <el-button type="primary" icon="DocumentAdd" @click="addAccount()"
              v-if="permissionIsShow.add">新增人员</el-button>
          </el-button-group>
          <el-input v-model="search" placeholder="人员姓名、身份证号、手机号"
            style="width: 250px;margin-left: 15px;margin-right: 15px" clearable></el-input>
          <el-button type="primary" icon="Search" @click="reqAccountData()">搜索</el-button>
        </div>

        <!--      表格-->
        <div style="height: calc(100vh - 134px)">
          <el-table :data="accountData" :row-style="{ height: '47px' }" style="width: 100%;height:calc(100% - 68px)"
            :header-cell-style="{ background: '#f4f3f9' }">
            <el-table-column prop="name" label="姓名" align="center" />
            <el-table-column prop="idCard" label="身份证号" align="center" />
            <el-table-column prop="sex" label="性别" align="center">
              <template #default="scope">
                <el-tag
                        :type="scope.row.sex === '0' ? 'success' : 'danger'"
                        disable-transitions> {{ Number(scope.row.sex) == '0' ? '男' : '女' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="telephone" label="联系电话" align="center" />
            <el-table-column prop="birthday" label="出生年月" align="center" />
            <el-table-column prop="address" label="住址" align="center" />
            <el-table-column prop="workUnit" label="工作单位" align="center" />
            <el-table-column fixed="right" label="操作" width="200" align="center"
              v-if="permissionIsShow.edit || permissionIsShow.delete || permissionIsShow.resetPassword">
              <template #default="scope">
                <el-button type="primary" size="small" icon="Edit" @click="editAccount(scope.row)"
                  v-if="permissionIsShow.edit">编辑</el-button>
                <el-button type="danger" size="small" icon="Delete" @click="deleteAccount(scope.row.id)"
                  v-if="permissionIsShow.delete">删除</el-button>
                <el-button type="primary" size="small" icon="Edit" @click="resetPassword(scope.row)"
                  v-if="permissionIsShow.resetPassword">重置密码</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--        页数导航栏-->
          <div class="footer">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[5, 10]"
              :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!--       新增人员-->
    <el-dialog v-model="disvisable" @close="cancel" :title="isEdit ? '修改' : '新增'" width="40%" align-center
      :style="{ maxHeight: '85vh', overflow: 'hidden' }">
      <el-form label-position="left" :model="accountForm" :rules="rules" ref="accountForm" label-width="15%"
        :style="{ maxHeight: 'calc(90vh - 120px)', overflowY: 'auto', }">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="accountForm.name" autocomplete="off" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="accountForm.idCard" autocomplete="off" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="accountForm.sex" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone">
          <el-input v-model="accountForm.telephone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="出生年月" prop="birthday">
          <el-date-picker v-model="accountForm.birthday" value-format="YYYY-MM-DD" type="date"
                          style="width: 100%" placeholder="请选择出生年月" clearable />
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input v-model="accountForm.address" placeholder="请输入住址" />
        </el-form-item>
        <el-form-item label="工作单位" prop="workUnit">
          <el-input v-model="accountForm.workUnit" placeholder="请输入工作单位" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAccountForm('accountForm')">提交
          </el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
import request from "@/utils/request";
import axios from 'axios';
import { serverIp } from '@/ipConfig/config';

const ruleFormRef = ref()
export default {
  name: 'Account',
  components: {
    serverIp
  },
  data() {
    return {
      search: "", //搜索
      serverIp: serverIp,
      accountForm: {},
      // 非空校验
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
        ],
        telephone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
        ],
        address: [
          { required: true, message: '请输入住址', trigger: 'blur' },
        ],
      },
      // 弹窗关闭
      disvisable: false,
      isEdit: false,
      // 图片预览弹窗
      previewVisible: false,
      previewImageUrl: '',
      // 分页数据
      currentPage: 1, //页码
      pageSize: 10, //页长
      total: 0,  //总表长
      accountData: [],

      // 登录用户信息
      loginUserInfo: {
        id: '',
        responsibleScope: '', //查询范围
        roleLevel: '', //角色等级
        unitId: '', //内设部门ID
        userRole: '', //角色ID
        permissions: [], // 按钮路径（数据库中的path）
      },
      // 按钮权限
      permissionIsShow: {
        add: false,
        edit: false,
        delete: false,
        resetPassword: false,
      },
    }
  },

  created() {
    const info = JSON.parse(localStorage.getItem("user"));
    this.loginUserInfo = {
      id: Number(info.id),
      responsibleScope: info.responsibleScope, //查询范围
      roleLevel: Number(info.roleLevel),
      unitId: Number(info.unitId),
      userRole: Number(info.userRole),
      permissions: info.permissions.filter(item => Number(item.menuId) === 37).map(item => item.path),
    }
    this.permissionIsShow = {
      add: this.loginUserInfo.permissions.includes('account-add'),
      edit: this.loginUserInfo.permissions.includes('account-edit'),
      delete: this.loginUserInfo.permissions.includes('account-delete'),
      resetPassword: this.loginUserInfo.permissions.includes('account-resetPassword'),
    }
    this.reqAccountData(); //加载地点数据
  },

  methods: {
    // 分页请求
    reqAccountData() {
      request.get("/account/page", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          param: this.search,
        }
      }).then(res => {
        if (res.code == '200') {
          this.accountData = res.data.records;
          this.total = res.data.total;
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.reqAccountData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.reqAccountData();
    },

    // 删除地点
    deleteAccount(val) {
      this.$confirm('是否确定删除该人员?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showClose: false,
        type: 'warning'
      }).then(() => {
        request.get("/account/delete/" + val).then(res => {
          if (res.code == "200") {
            this.$message({
              type: "success",
              message: "删除成功"
            })
            this.reqAccountData();
          }
        })
      })
        .catch(() => {
        });
    },

    // 新增Account
    addAccount() {
      this.disvisable = true
      this.isEdit = false
    },

    // 编辑表单数据
    editAccount(val) {
      this.disvisable = true;
      this.isEdit = true;
      Object.assign(this.accountForm, val);
    },

    // 二级表单的提交
    submitAccountForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 发送请求
          request.post("/account/edit", this.accountForm).then(res => {
            if (res.code === '400') {
              this.$message({
                type: "warning",
                message: res.msg
              })
            } else if (res.code === '200') {
              this.$message({
                type: "success",
                message: "提交成功"
              })
              this.reqAccountData();
              this.cancel();
            }
          })
        } else {
          this.$message.warning("请正确填写表单")
        }
      });
    },

    cancel() {
      this.disvisable = false
      this.accountForm = {}
      this.$refs.accountForm.resetFields()
    },

    // 预览图片
    previewImage(url) {
      this.previewVisible = true;
      this.previewImageUrl = url;
    },
    // 重置密码
    resetPassword(row) {
      // 询问是否重置密码
      this.$confirm('是否重置密码为123456?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showClose: false,
        type: 'warning'
      }).then(() => {
        request.get("/account/resetPassword", {
          params: {
            id: row.id
          }
        }).then(res => {
          if (res.code === '200') {
            this.$message({
              type: "success",
              message: "重置成功"
            })
            this.reqAccountData();
          }
        })
      })
        .catch(() => {
        });
    },
  },
}

</script>
<style scoped>
#roleSpan {
  color: black;
  text-decoration: none;
}

:deep(.el-form-item__label) {
  line-height: 18px;
}

/*   外框架   */
.framework1 {
  height: calc(100vh - 88px);
  width: calc(100vh - 200px);
  margin-left: 8px;
  border: solid 1px #D3D3D3;
}

/*   内框架   */
.framework2 {
  height: calc(100vh - 92px);
  border: solid 1px #D3D3D3;
}

/*   表格大标题   */
.header {
  font-size: 16px;
  font-weight: bold;
  padding: 4px 20px;
  background-color: #D3D3D3;
}

/*   表格按键组   */
.button_group {
  padding: 4px 10px;
  background-color: #DDDDDD;
}

/*   表格分页处   */
.footer {
  padding: 4px 10px;
  background-color: #f4f3f9;
}

.el-dialog-image {
  height: 100px;
  width: 200px;
  margin-top: 10px;
  margin-right: 10px;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
